from fastapi import APIRouter,Depends
from sqlalchemy.orm import Session
from sqlalchemy import desc,asc,and_
from vendor.extend.courier import *
from model.ground_colliery import GroundColliery as CollieryTable,FormBody,EditBody
from db.mysql import get_db
from loguru import logger


DataColliery = APIRouter()



@DataColliery.post('/add')
async def add_colliery(itme:FormBody,db: Session = Depends(get_db)):
    item = itme.dict()

    add_data=CollieryTable(
        identifier=item.get('identifier',''),
        create_time=int(time.time())
    )
    try:
        # 执行一些数据库操作
        db.add(add_data)
        db.flush()
        db.commit()
        db.refresh(add_data)
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("矿井 添加 出错:{}", e)
        return Error(msg='矿井添加失败')


    return Success(msg='矿井添加成功',data={'colliery_id':add_data.id,'create_time':add_data.create_time})


@DataColliery.post('/edit')
async def edit_colliery(item:EditBody,db: Session = Depends(get_db)):
    item_dict = item.dict()
    edit_data={
        'identifier':item_dict.get('identifier',''),
        'update_time':int(time.time())
    }

    try:
        # 执行一些数据库操作
        db.query(CollieryTable).filter_by(id=item_dict.get('colliery_id',0)).update(edit_data)
        db.commit()
    except Exception as e:
        # 手动回滚会话并重新抛出异常
        db.rollback()
        logger.error("矿井信息 更新 出错:{}", e)
        return Error(msg='矿井添加失败')

    return Success(msg='更新成功',data=edit_data)


@DataColliery.get('/getlist')
async def colliery_list(db: Session = Depends(get_db)):
    data_list=db.query(CollieryTable).order_by(CollieryTable.id.desc()).all()
    list_data=[]
    for info in data_list:
        list_data.append({
            "id":info.id,
            "identifier":info.identifier,
            "create_time":info.create_time
        })
    return Success(msg='矿井列表',data=list_data)